package com.tjcm.tjcminspectmanager;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import cn.emagsoftware.ui.ToastManager;
import cn.emagsoftware.ui.dialog.DialogManager;
import cn.emagsoftware.ui.staticmanager.StaticManager;
import cn.emagsoftware.util.AsyncWeakTask;
import cn.emagsoftware.util.CodeException;
import cn.emagsoftware.util.DateUtilities;
import cn.emagsoftware.util.LogManager;

import com.tjcm.tjcminspectmanager.manager.NetManager;
import com.tjcm.tjcminspectmanager.model.ContentItem;
import com.tjcm.tjcminspectmanager.model.KeyValue;
import com.tjcm.tjcminspectmanager.model.User;

public class TaskProcessSubmitActivity extends BaseActivity
{
    private LocationManager  mgr      = null;
    private LocationListener listener = null;

    private String           modelId  = "";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        if (!LoginActivity.IS_APP_RUNNING)
        {
            StaticManager.restartAppWhenDalvikRecycled(this, LoginActivity.class);
            return;
        }

        Intent intent = getIntent();
        final String taskId = intent.getStringExtra("TASK_ID");
        String taskType = intent.getStringExtra("TASK_TYPE");
        final User user = (User) intent.getSerializableExtra("USER");

        setContentView(R.layout.taskprocesssubmit);

        final LinearLayout itemWrap = (LinearLayout) findViewById(R.id.item_wrap);
        final TextView title = (TextView) findViewById(R.id.title);
        final EditText time = (EditText) findViewById(R.id.time);
        final EditText lon = (EditText) findViewById(R.id.lon);
        final EditText lat = (EditText) findViewById(R.id.lat);
        Button submit = (Button) findViewById(R.id.submit);
        Button back = (Button) findViewById(R.id.back);

        time.setText(DateUtilities.getFormatDate("yyyy-MM-dd HH:mm:ss"));
        lon.setText("0.00000");
        lat.setText("0.00000");
        mgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        listener = new LocationListener()
        {
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras)
            {
                // TODO Auto-generated method stub
                time.setText(DateUtilities.getFormatDate("yyyy-MM-dd HH:mm:ss"));
                lon.setText("0.00000");
                lat.setText("0.00000");
            }

            @Override
            public void onProviderEnabled(String provider)
            {
                // TODO Auto-generated method stub
                time.setText(DateUtilities.getFormatDate("yyyy-MM-dd HH:mm:ss"));
                lon.setText("0.00000");
                lat.setText("0.00000");
            }

            @Override
            public void onProviderDisabled(String provider)
            {
                // TODO Auto-generated method stub
                time.setText(DateUtilities.getFormatDate("yyyy-MM-dd HH:mm:ss"));
                lon.setText("0.00000");
                lat.setText("0.00000");
            }

            @Override
            public void onLocationChanged(Location location)
            {
                // TODO Auto-generated method stub
                time.setText(DateUtilities.getFormatDate(new Date(location.getTime()), "yyyy-MM-dd HH:mm:ss"));
                lon.setText(location.getLongitude() + "");
                lat.setText(location.getLatitude() + "");
            }
        };
        mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, listener);
        submit.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                StringBuilder strBuilder = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                strBuilder.append("<root>");
                strBuilder.append("<param>");
                strBuilder.append("<dw_user>" + user.userId + "</dw_user>");
                strBuilder.append("<model_id>" + modelId + "</model_id>");
                strBuilder.append("<taskId>" + taskId + "</taskId>");
                strBuilder.append("<report_time>" + time.getText() + "</report_time>");
                strBuilder.append("<longitude>" + lon.getText() + "</longitude>");
                strBuilder.append("<latitude>" + lat.getText() + "</latitude>");
                strBuilder.append("</param>");
                strBuilder.append("<data>");
                for (int i = 1; i < itemWrap.getChildCount() - 3; i++)
                {
                    View view = ((ViewGroup) itemWrap.getChildAt(i)).getChildAt(1);
                    String name = (String) view.getTag();
                    String value = "";
                    if (view instanceof Spinner)
                    {
                        value = (String) ((Spinner) view).getSelectedItem();
                    } else if (view instanceof EditText)
                    {
                        value = ((EditText) view).getText().toString();
                    }
                    strBuilder.append("<row name=\"" + name + "\">" + value + "</row>");
                }
                strBuilder.append("</data>");
                strBuilder.append("</root>");
                new AsyncWeakTask<String, Object, Object>(TaskProcessSubmitActivity.this)
                {
                    protected void onPreExecute(Object[] objs)
                    {
                        ProgressDialog dialog = DialogManager.showProgressDialog((Context) objs[0], R.string.generic_dialog_title, R.string.taskprocesssubmit_btn_submit_process, null, null, true,
                                false);
                        dialog.setOnCancelListener(new DialogInterface.OnCancelListener()
                        {
                            @Override
                            public void onCancel(DialogInterface dialog)
                            {
                                // TODO Auto-generated method stub
                                cancel(true);
                            }
                        });
                        addToWeakReference(dialog);
                    }

                    protected Object doInBackgroundImpl(String... arg0) throws Exception
                    {
                        NetManager.submitTaskTemplate(arg0[0]);
                        return null;
                    }

                    protected void onPostExecute(Object[] objs, Object result)
                    {
                        ((ProgressDialog) objs[1]).dismiss();
                        final Activity activity = (Activity) objs[0];
                        DialogManager.showAlertDialog(activity, R.string.generic_dialog_title, R.string.taskprocesssubmit_btn_submit_success, new int[] { R.string.generic_dialog_btn_ok }, null, true,
                                false).setOnDismissListener(new DialogInterface.OnDismissListener()
                        {
                            @Override
                            public void onDismiss(DialogInterface dialog)
                            {
                                // TODO Auto-generated method stub
                                activity.setResult(100);
                                activity.finish();
                            }
                        });
                    }

                    protected void onException(Object[] objs, Exception e)
                    {
                        LogManager.logE(TaskProcessSubmitActivity.class, "submit template failed.", e);
                        ((ProgressDialog) objs[1]).dismiss();
                        int resId;
                        if (e instanceof CodeException)
                        {
                            CodeException excep = (CodeException) e;
                            if (NetManager.CODE_IO.equals(excep.getCode()))
                                resId = R.string.generic_error_io;
                            else
                                resId = R.string.taskprocesssubmit_btn_submit_failed;
                        } else
                        {
                            resId = R.string.generic_error;
                        }
                        DialogManager.showAlertDialog((Context) objs[0], R.string.generic_dialog_title, resId, new int[] { R.string.generic_dialog_btn_ok }, null, true, false);
                    }
                }.execute(strBuilder.toString());
            }
        });
        back.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                finish();
            }
        });
        new AsyncWeakTask<String, Object, ContentItem[]>(TaskProcessSubmitActivity.this)
        {
            protected void onPreExecute(Object[] objs)
            {
                ProgressDialog dialog = DialogManager.showProgressDialog((Context) objs[0], R.string.generic_dialog_title, R.string.taskprocesssubmit_init, null, null, true, false);
                dialog.setOnCancelListener(new DialogInterface.OnCancelListener()
                {
                    @Override
                    public void onCancel(DialogInterface dialog)
                    {
                        // TODO Auto-generated method stub
                        cancel(true);
                    }
                });
                addToWeakReference(dialog);
            }

            protected ContentItem[] doInBackgroundImpl(String... arg0) throws Exception
            {
                return NetManager.loadTaskTemplate(arg0[0]);
            }

            protected void onPostExecute(Object[] objs, ContentItem[] result)
            {
                ((ProgressDialog) objs[1]).dismiss();
                Context context = (Context) objs[0];
                if (result.length == 0)
                {
                    ToastManager.showLong(context, R.string.taskprocesssubmit_init_empty);
                    return;
                }
                String[] commonValues = result[0].getCommonValues();
                String colon = getString(R.string.generic_colon);
                title.setText(commonValues[0].endsWith(colon) ? commonValues[0] : commonValues[0] + colon);
                modelId = commonValues[1];
                float scale = getResources().getDisplayMetrics().density;
                LinearLayout.LayoutParams keyParams = new LinearLayout.LayoutParams((int) (90 * scale + 0.5f), LinearLayout.LayoutParams.WRAP_CONTENT);
                keyParams.gravity = Gravity.CENTER_VERTICAL;
                LinearLayout.LayoutParams valueParams = new LinearLayout.LayoutParams((int) (190 * scale + 0.5f), (int) (42 * scale + 0.5f));
                valueParams.gravity = Gravity.CENTER_VERTICAL;
                LinearLayout.LayoutParams wrapParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                wrapParams.gravity = Gravity.CENTER_HORIZONTAL;
                wrapParams.topMargin = (int) (12 * scale + 0.5f);
                int index = 1;
                for (KeyValue key : result[0].getKeyValues())
                {
                    LinearLayout item = new LinearLayout(context);
                    TextView name = new TextView(context);
                    name.setText(key.name.endsWith(colon) ? key.name : key.name + colon);
                    item.addView(name, keyParams);
                    if (key.value.contains("##"))
                    {
                        String[] partTexts = key.value.split("##");
                        String[] optionTexts = partTexts[1].split("==");
                        Spinner spinner = new Spinner(context);
                        List<String> optionList = Arrays.asList(optionTexts);
                        optionList.add(0, "");
                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, optionList);
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        spinner.setAdapter(adapter);
                        spinner.setTag(key.name);
                        item.addView(spinner, valueParams);
                    } else
                    {
                        EditText edit = new EditText(context);
                        edit.setTag(key.name);
                        item.addView(edit, valueParams);
                        if (index == 1)
                            edit.requestFocus();
                    }
                    itemWrap.addView(item, index++, wrapParams);
                }
            }

            protected void onException(Object[] objs, Exception e)
            {
                LogManager.logE(TaskProcessSubmitActivity.class, "load template failed.", e);
                ((ProgressDialog) objs[1]).dismiss();
                ToastManager.showLong((Context) objs[0], R.string.taskprocesssubmit_init_failed);
            }
        }.execute(taskType);
    }

    @Override
    protected void onDestroy()
    {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (listener != null)
            mgr.removeUpdates(listener);
    }

}